<%@ include file="/WEB-INF/views/commonJSTL.jsp" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>${s_UserPharmacy.pharmacy.name}</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<%@ include file="/WEB-INF/views/commonResources.jsp" %>

<fmt:message key="form.selected" var="selected"/>	

<script type="text/javascript">
$(function() {
    
	  $.datepicker.regional['es'] = 
	  {
	  closeText: 'Cerrar', 
	  prevText: 'Previo', 
	  nextText: 'Próximo',
	  
	  monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
	  'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
	  monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
	  'Jul','Ago','Sep','Oct','Nov','Dic'],
	  monthStatus: 'Ver otro mes', yearStatus: 'Ver otro año',
	  dayNames: ['Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado'],
	  dayNamesShort: ['Dom','Lun','Mar','Mie','Jue','Vie','Sáb'],
	  dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sa'],
	  dateFormat: 'dd/mm/yy', firstDay: 0, 
	  initStatus: 'Selecciona la fecha', isRTL: false};
	  $.datepicker.setDefaults($.datepicker.regional['es']);
});
	
	var listVisitorTemp = [];
	<c:forEach var="item" items="${listVisitor}">
		var userProvider = {userProviderId:"<c:out value="${item.userproviderPK.userProviderId}"/>",providerId:"<c:out value="${item.userproviderPK.providerId}"/>",name:"<c:out value="${item.name}"/>"};
		listVisitorTemp.push(userProvider);
	</c:forEach>

$(document).ready(function(){
	$('.numbersOnly').keyup(function () {
        if (this.value != this.value.replace(/[^0-9\.]/g, '')) {
           this.value = this.value.replace(/[^0-9\.]/g, '');
        }
    });
	$('.lettersOnly').keyup(function () {
        if (this.value != this.value.replace(/[^A-Za-z\s]/g, '')) {
           this.value = this.value.replace(/[^A-Za-z\s]/g, '');
        }
    });
	
	loadTableInSearchByProviderId('');

	$("input[name='searchTypeBuy']").change(function(){
        var searchTypeBuyValue = parseInt($("input[name='searchTypeBuy']:checked").val(),10);
        if(searchTypeBuyValue == 1){
        	$("#divShowBr").css("display", "block");
            $("#typeBuyDiv").css("display", "block");
        }else{
            $("#divShowBr").css("display", "none");
            $("#typeBuyDiv").css("display", "none");
        }
    }); 	
	$("#_searchByList").change(function() {
		$.ajax({ 
    		type: "GET",
    		url	: 'loadTableTempBySelect',
       	   	dataType: "json",		
            data: {selectId:$("#_searchByList").val()},
       	    success:function(data){   
       	    	if($("#_searchByList").val() == 1)
       	    		loadTableInSearch2(loadListProductTemp(data),loadListPharmacyStockTemp(data)); 
       	    	else
       	    		if($("#_searchByList").val() == 2 || $("#_searchByList").val() == '')
       	    			loadTableInSearchByProviderId('');
       	    		else
       	    			if($("#_searchByList").val() == 3)
       	    				loadTableInSearch(loadListProductTemp(data),loadListPharmacyStockTemp(data)); 
       		}, 
       		error: 	function(){alert('Error en request..');} });
	});	
	$("#searchName").keyup(function() {
		if($("#_providerId").val() != '')
			loadTableInSearchByProviderIdByName($("#_providerId").val(),$("#searchName").val());
		else
			alert('Seleccione Proveedor');
		/*
		var rows = $("#fbody").find("tr").hide();
		var data = this.value.split(" ");
		$.each(data, function(i, v) {
			rows.filter(":contains('" + v + "')").show();
		});*/
	});
	$("#searchCode").keyup(function() {
		if($("#_providerId").val() != '')
			loadTableInSearchByProviderIdByCode($("#_providerId").val(),$("#searchCode").val());
		else
			alert('Seleccione Proveedor');
	});
	$("#searchCodeBar").keyup(function() {
		if($("#_providerId").val() != '')
			loadTableInSearchByProviderIdByCodeBar($("#_providerId").val(),$("#searchCodeBar").val());	
		else
			alert('Seleccione Proveedor');
	}); 
	
	$("#dialogNewPharmacyProduct").dialog({autoOpen: false, height: 655, width: 750, modal: true,
		open: function(event, ui){		
			/*
			$("input:checkbox").prop('checked', true);
        	$("input[type=checkbox]").prop('checked', true);
        	checkbox_1($("#checkbox_1"));
        	checkbox_2($("#checkbox_2"));
        	*/ 
        	if(!$('#checkbox_1').is(':checked') && !$('#checkbox_2').is(':checked')){
        		//alert($('#checkbox_1').is(':checked') + '  h  '+$('#checkbox_2').is(':checked'));
        		$( "#checkbox_1" ).prop( "checked", true );	
        		checkbox_1($("#checkbox_1"));
        		$( "#checkbox_2" ).prop( "checked", true );	
        		checkbox_2($("#checkbox_2"));
        	}
        	
        	if($('#checkbox_1').is(':checked')){
        		$( "#checkbox_1" ).prop( "checked", true );	
        		checkbox_1($("#checkbox_1"));
        	}
        	if($('#checkbox_2').is(':checked')){
        		$( "#checkbox_2" ).prop( "checked", true );	
        		checkbox_2($("#checkbox_2"));	
        	}
		},
		buttons: {
            "Aceptar": function() {
            	var flag = $("#formPharmacyProduct").valid();
                if(flag){
                	$.ajax({ 
	            		type: "POST",
	            		url	: 'formNewPharmacyProduct',
	            		dataType: "json",
                        data: $('#formPharmacyProduct').serialize(),
		           	    success:function(data){
		           	    	alert(data.msg);
		           	    	$("#dialogNewPharmacyProduct").dialog( "close" );
		           	    	loadTableInSearchByProviderId($("#_providerId").val());
		           		}, 
		           		error: 	function(){alert('Error al Agregar Datos..');} }); 
                } 
            },
            Cancelar: function() { $( this ).dialog( "close" );}
		},
		close: function(){ $( this ).dialog( "close" ); }
	});		
	$(".addNewVisitor").click(function(){
		if($("#_providerId").val() != ''){
			$("#providerProviderId").val($("#_providerId").val());
			$("#dialogNewVisitor").load("formNewVisitor",function(){
				openDialogModalForm("#dialogNewVisitor","Nuevo Visitador",null);
			});
		}else{
			alert('seleccione el proveedor');
		}
	});	
	$("#_providerId").change(function(){ 
		var providerId = $(this).val();		
		loadTableInSearchByProviderId(providerId);
		var element = $("#_visitorId");
		element.empty().append("<option value=''><c:out value="${selected}"/></option>");
		if(providerId != ""){
			for(var i=0; i<listVisitorTemp.length; i++){
				var userProvider = listVisitorTemp[i];
				if(providerId == userProvider.providerId){
					element.append("<option value='"+userProvider.userProviderId+"'>"+userProvider.name+"</option>");
				}
			}
		}
	});	
	$.fn.selectRadioTypePayment = function(obj){
		removeElement("idContainer");
    	if(obj.checked)
        	$("#MainContainer").generateDivMainContainer(obj.value);
    }
	jQuery.fn.generateDivMainContainer = function(value){
		$(this).each(function(){
                    elem = $(this);   
                    text_insert ='	<div style="clear:both;" id="idContainer">';                      
                    if(value == 1){
                    	var fecha_actual = new Date();
                    	var tempMonth=(fecha_actual.getMonth()+1);
               			var tempDate=fecha_actual.getDate();
               			
               			if ((fecha_actual.getMonth()+1) < 10) tempMonth = '0' + (fecha_actual.getMonth()+1);
               			if (fecha_actual.getDate() < 10) tempDate = '0' + (fecha_actual.getDate());
               			
        				var string_date_new_other=tempDate+"/"+tempMonth+"/"+fecha_actual.getFullYear();
                    	
        				text_insert +='	<div style="clear:both;">';
        				text_insert +='		<label class="form_align25" >Monto a Cobrar :</label>';
        				text_insert +='		<input type="text" name="amount1" id="amount1" value="60.00" class="required number form_input_align numbersOnly" maxlength="6" title="Ingrese el monto a Cobrar."/>';
        				text_insert +='		<label class="error">*</label>';
        				text_insert +='	</div>';
        				text_insert +='	<div style="clear:both;">';
        				text_insert +='		<label class="form_align25" >Fecha de Vencimiento :</label>';
        				text_insert +='		<input type="text" name="expirationDate1" id="expirationDate1" onclick="$(this).datepicker({changeMonth: true,changeYear: true,numberOfMonths: 1,minDate: \'0D\',});$(this).datepicker().datepicker(\'show\');" value="'+string_date_new_other+'" readonly="true" class="required form_input_align" maxlength="25" title="Ingrese la fecha.."/>';
        				text_insert +='		<label class="error">*</label>';
        				text_insert +='	</div>';
                    }  
                    
					if(value == 3){
                    	var frecPayment = new Array ("Semanal","Mensual","Bimestral","Trimestral","Semestral","Anual");
                    	text_insert +='	<div style="clear:both;">';
                    	text_insert +='		<label class="form_align25" >Cantidad de Pagos:</label>';
                    	text_insert +='		<select name="amountPayment" id="amountPayment" onChange="loadPaidPlanTable()" class="required form_input_align" title="Seleccione la cantidad de pagos.">';
                    	text_insert +='			<option value="">Seleccione</option>';
		                 for(var i=2;i<=30;i++){
		                	 text_insert += '	<option value="'+i+'">'+i+' Cuotas</option>';
	                    }
		                text_insert +='		</select>';
		                text_insert +='	</div>';
		                text_insert +='	<div style="clear:both;">';
		                text_insert +='		<label class="form_align25" >Frecuencia de Pagos:</label>';
		                text_insert +='		<select name="frequencyPayment" id="frequencyPayment" onChange="loadPaidPlanTable()" class="required form_input_align" title="Seleccione la frecuencia de pagos.">';
		                text_insert +='			<option value="">Seleccione</option>';
		                for(var p=0; p< frecPayment.length;p++){
		                	text_insert += '	<option value="'+p+'">'+frecPayment[p]+'</option>';
	                    }
		                text_insert +='		</select>';
		                text_insert +='	</div>';
		                text_insert +='	<br/>';
		                text_insert +='	<div style="clear:both;">';
		                text_insert +='		<label class="form_align25">Pagos:</label>';
		                text_insert +='     <div id="paidPlan" style="with:50px"></div>'; 
		                text_insert +='     <div id="res" style="with:50px"></div>'; 
		                text_insert +='	</div>';
                    }
					text_insert +='</div>';
                    elem.before(text_insert);
		});
		return this;
    }		 
	$("#dialogNewVisitor").dialog({autoOpen: false, height: 480, width: 700, modal: true,
		buttons: {
            "Aceptar": function() {
            	var flag = $("#formVisitor").valid();
                if(flag){
                	$.ajax({ 
	            		type: "POST",
	            		url	: 'formNewVisitor',
		           	   	dataType: "json",			        		
                        data: $('#formVisitor').serialize(),
		           	    success:function(visitor){
		           	    	alert(visitor.userProviderId);
		           	    	/*
		           	    	var element = $("#_visitorId");
    			        	element.empty().append("<option value=''>Seleccione</option>");    			        	
    			        	if(visitor.listName[0] != ''){
    			        		for(var i=0; i<visitor.visitors.length; i++){
    			        			var obj = visitor.visitors[i];
    			        			var selec = '';
    			        			if(obj.userproviderPK.userProviderId == visitor.id)
       			                    	selec='selected="selected"';
    			        			element.append("<option value='"+obj.userproviderPK.userProviderId+"' "+selec+">"+obj.name+"</option>");
    			        		}
    			        	}      			        	
    			        	*/
		           	    	$("#dialogNewVisitor").dialog( "close" );
		           	    	
		           		}, 
		           		error: 	function(){alert('Error en request..');} }); 
            	}
            },
            Cancelar: function() { $( this ).dialog( "close" );}
		},
		close: function(){ $( this ).dialog( "close" ); }
	});	
});	

	function loadTableInSearch2(data,listPharmacyStockTemp){
		var listProductT = [];
		for(var i=0;i<data.length;i++){
			var obj = data[i];
			var countVal = 0;
			for (var j = 0; j < listPharmacyStockTemp.length; j++) {
				var ps = listPharmacyStockTemp[j];
				var countItems = 0;
				if(ps.itemsCollection.length > 0){
					for (var m = 0; m < ps.itemsCollection.length; m++) {
						var itemElement = ps.itemsCollection[m];
						if(itemElement.productId == obj.productId)
							countItems++;
					}
				}					
				countVal=countVal+countItems;
			}
			if(obj.repositionLevel > countVal)
				listProductT.push(obj);		
		}
		loadTableInSearch(listProductT,listPharmacyStockTemp);
	}
		
	function loadTableInSearch(data,listPharmacyStockTemp){
		var texto_insertar='';
			texto_insertar +='	<table class="tabla_decorado" style="width: 100%">';
			texto_insertar +='    	<thead>';
			texto_insertar +='			<tr>';
			texto_insertar +='          	<th width="3%" class="th_decoradoRowspan"><fmt:message key="table.num"/></th>';
			texto_insertar +='          	<th width="15%" class="th_decoradoRowspan"><fmt:message key="table.name"/></th>';
			texto_insertar +='				<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.genericName"/></th>';
			texto_insertar +='				<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.therapeuticAction"/></th>';
			texto_insertar +='				<th width="5%" class="th_decoradoRowspan"><fmt:message key="table.compositionType"/></th>';
			texto_insertar +='				<th width="15%" class="th_decoradoRowspan"><fmt:message key="table.stock"/></th>';
			texto_insertar +='				<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.stockQuantity"/></th>';
			texto_insertar +='				<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.code"/></th>';
			texto_insertar +='				<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.codeBar"/></th>';
			texto_insertar +='				<th width="5%" class="th_decoradoRowspan"><fmt:message key="table.repositionLevel"/></th>';
			texto_insertar +='				<th width="7%" class="th_decoradoRowspan"><fmt:message key="table.actions"/></th>';
			texto_insertar +='      	</tr>';
			texto_insertar +='    	</thead>';
			texto_insertar +='    	<tbody id="fbody">';
			if($("#_providerId").val() != '')
			for(var i=0;i<data.length;i++){
				var obj = data[i];
				texto_insertar +='		<tr class="tr_decorado">';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+(i+1)+'</td>';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+obj.name+'</td>';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+obj.genericName+'</td>';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+obj.therapeuticActionName+'</td>';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+obj.typeComposition+'</td>';
				var nameStock = "";
				for (var j = 0; j < listPharmacyStockTemp.length; j++) {
					var ps = listPharmacyStockTemp[j];
					nameStock=nameStock+ps.nameStock+' <br/>';
				}				
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+nameStock+'</td>';
				var countVal = "";
				for (var j = 0; j < listPharmacyStockTemp.length; j++) {
					var ps = listPharmacyStockTemp[j];
					var countItems = 0;
					if(ps.itemsCollection.length > 0){
						for (var m = 0; m < ps.itemsCollection.length; m++) {
							var itemElement = ps.itemsCollection[m];
							if(itemElement.productId == obj.productId)
								countItems++;
						}
					}					
					countVal=countVal+countItems+' Unidades  <br/>';
				}
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+countVal+'</td>';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+((obj.code != null)?obj.code:'')+'</td>';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+((obj.codeBar != null)?obj.codeBar:'')+'</td>';
				texto_insertar +='			<td class="th_decorado" style="text-align: center">'+((obj.repositionLevel != null)?obj.repositionLevel:'')+'</td>';
				texto_insertar +='			<td class="td_decoradoDerecha" style="text-align: center"><input type="button" id="button_'+obj.productId+'_'+obj.providerId+'" value="<fmt:message key="button.add"/> <fmt:message key="title.product"/>"" class="botonRep" onClick="addNewPharmacyProduct(this)" title="<fmt:message key="onclick.add"/> <fmt:message key="title.product"/>." /></td>';
				texto_insertar +='		</tr>';
			}			
			if(data.length == 0 || $("#_providerId").val() == '')
				texto_insertar +='		<tr class="tr_decorado"><td class="td_decorado" colspan="9" style="text-align:center"><span style="color:red"><fmt:message key="show.noExistSearchProducts"/></span></td></tr>';
			texto_insertar +='    	</tbody>';
			texto_insertar +='	</table>';
		$("#mainContainerSearch").html(texto_insertar);
	}
	function loadTableInSearchByProviderIdByName(providerId,name){		
		$.ajax({ 
    		type: "GET",
    		url	: 'loadTableTempByName',
       	   	dataType: "json",		
            data: {providerId:providerId,name:name},
       	    success:function(data){   
       			loadTableInSearch(loadListProductTemp(data),loadListPharmacyStockTemp(data));      	    	
       		}, 
       		error: 	function(){alert('Error en request..');} }); 	
	}
	function loadTableInSearchByProviderIdByCode(providerId,code){		
		$.ajax({ 
    		type: "GET",
    		url	: 'loadTableTempByCode',
       	   	dataType: "json",		
            data: {providerId:providerId,code:code},
       	    success:function(data){   
       			loadTableInSearch(loadListProductTemp(data),loadListPharmacyStockTemp(data));      	    	
       		}, 
       		error: 	function(){alert('Error en request..');} }); 	
	}
	function loadTableInSearchByProviderIdByCodeBar(providerId,codeBar){		
		$.ajax({ 
    		type: "GET",
    		url	: 'loadTableTempByCodeBar',
       	   	dataType: "json",		
            data: {providerId:providerId,codeBar:codeBar},
       	    success:function(data){   
       			loadTableInSearch(loadListProductTemp(data),loadListPharmacyStockTemp(data));      	    	
       		}, 
       		error: 	function(){alert('Error en request..');} }); 	
	}
	function loadTableInSearchByProviderId(providerId){		
		$.ajax({ 
    		type: "GET",
    		url	: 'loadTableTemp',
       	   	dataType: "json",		
            data: {providerId:providerId},
       	    success:function(data){   
       			loadTableInSearch(loadListProductTemp(data),loadListPharmacyStockTemp(data));      	    	
       		}, 
       		error: 	function(){alert('Error en request..');} }); 	
	}	
	function loadListProductTemp(data){
		var listProductTemp = [];
		for (var i = 0; i < data.listProductActive.length; i++) {
			var itemProduct = data.listProductActive[i];
			var nameComposition = "";
			for (var j = 0; j < itemProduct.compositionCollection.length; j++) {
				var itemComposition = itemProduct.compositionCollection[j];
				if(itemProduct.productPK.productId == itemComposition.product.productPK.productId && itemProduct.productPK.providerId == itemComposition.product.productPK.providerId){
					nameComposition = itemComposition.typeCompositionId.name;
				}
			}
			var product = {	productId:itemProduct.productPK.productId,
						providerId:itemProduct.productPK.providerId,
						name:itemProduct.name,
						repositionLevel:((itemProduct.pharmacyProduct != null)?itemProduct.pharmacyProduct.repositionLevel:''),
						genericName:itemProduct.genericName,
						therapeuticActionName:itemProduct.activeSubstanceId.name,
						code:itemProduct.code,
						typeComposition:nameComposition,
						codeBar:itemProduct.codeBar};
			listProductTemp.push(product);
		}
		return listProductTemp;
	}
	
	function loadListPharmacyStockTemp(data){
		listPharmacyStockTemp = [];  
		for (var i = 0; i < data.listPharmacyStock.length; i++) {
			var itemPharmacyStock = data.listPharmacyStock[i];
			var listItemsTemp = [];
			for (var j = 0; j < itemPharmacyStock.stock.itemCollection.length; j++) {
				var itemItem2 = itemPharmacyStock.stock.itemCollection[j];
				if(itemItem2.state == 1){
					var itemLocal = {	itemId:itemItem2.itemPK.itemId,
								packageId:itemItem2.itemPK.packageId,		
								productId:itemItem2.package1.pharmacyproduct.pharmacyproductPK.productId};
					listItemsTemp.push(itemLocal);
				}
			}
			var pharmacyStock = {	stockId:itemPharmacyStock.pharmacystockPK.stockId,
						pharmacyId:itemPharmacyStock.pharmacystockPK.pharmacyId,
						itemsCollection:listItemsTemp,
						nameStock:itemPharmacyStock.stock.name};
			listPharmacyStockTemp.push(pharmacyStock);
		}
		return listPharmacyStockTemp;
	}
	function addNewPharmacyProduct(obj){		
		var element = $(obj);		
		var value = (element.attr("id")).split("_");
		if($('#_providerId').val() != '' || $('#_searchByList').val() != ''){
			$("#dialogNewPharmacyProduct").load("formNewPharmacyProduct?_productId="+value[1]+"&_providerId="+value[2],function(){
				openDialogModalForm("#dialogNewPharmacyProduct","Nuevo Producto",null);
			});
		}else
				alert('seleccione el proveedor');		
	}	
	function removeElement(id){
	    obj = document.getElementById(id);
	    if(obj){
	        padre = obj.parentNode;
	        padre.removeChild(obj);
	    }
	}
	function sumUp(cont){
    	var temp=0;
    	var html = "";
    	for(var i=0; i<cont; i++){
			var value = $("#amount3_"+i).val();
			var element=0;
    		if(value.length > 0)
    			element=parseFloat($("#amount3_"+i).val());	
    		temp = temp+element;        		
    	}
    	html ='		<label class="form_align25" >&nbsp;</label><h3 style="color:#004080;margin:3px 0px 3px 0px;">Total: '+temp.toFixed(2)+' Bs.</h3>';
		$("#res").html(html);
	}
	function loadPaidPlanTable(){
        	var amountPayment 	= $("#amountPayment").val();
        	var frequencyPayment= $("#frequencyPayment").val();
        	var text_insert 	= "";
        	if(amountPayment.length > 0 && frequencyPayment.length){
        		amountPayment = parseInt(amountPayment,10);
        		frequencyPayment = parseInt(frequencyPayment,10);
        		text_insert +='		<table class="tabla_decorado" style="">';
        		text_insert +='    		<thead>';
        		text_insert +='				<tr>';
        		text_insert +='          		<th width="30%" class="th_decoradoRowspan">Fecha de Vencimiento</th>';
        		text_insert +='          		<th width="50%" class="th_decoradoRowspan">Detalle</th>';
        		text_insert +='					<th width="20%" class="th_decoradoRowspan">Importe</th>';
        		text_insert +='      		</tr>';
        		text_insert +='    		</thead>';
        		text_insert +='    		<tbody>';
            	var date_now = new Date();
	           	var nmonth=0;
	           	var ndays=0;
	           	var years=0;
	           	switch(parseInt(frequencyPayment,10)){
	             	case 0:
	                	ndays=7;
	             	  break;
	             	case 1:
	                	nmonth=1;
	             	  break;
	             	case 2:
	                	nmonth=2;
	             	  break;
	             	case 3:
	                	nmonth=3;
	             	  break;
	             	case 4:
	                	nmonth=6;
	             	  break;
	             	default:
	             		years=1;
             	}
            	var date_new_other = new Date();
       			var string_date_new_other="";
       			
           		for(var i=0; i<amountPayment; i++){
           			if(parseInt(frequencyPayment,10) == 0){
           				date_new_other=new Date(date_now.getFullYear(),date_now.getMonth(),(date_now.getDate()+ndays));
           			}
           			if(parseInt(frequencyPayment,10) >= 1 && parseInt(frequencyPayment,10) <= 4){
           				date_new_other=new Date(date_now.getFullYear(),(date_now.getMonth()+nmonth),date_now.getDate());
           			}
           			if(parseInt(frequencyPayment,10) == 5){
           				date_new_other=new Date(((date_now.getFullYear())+years),date_now.getMonth(),date_now.getDate());
           			}
           			var tempMonth=(date_new_other.getMonth()+1);
           			var tempDate=date_new_other.getDate();
           			if ((date_new_other.getMonth()+1) < 10) tempMonth = '0' + (date_new_other.getMonth()+1);
           			if (date_new_other.getDate() < 10) tempDate = '0' + (date_new_other.getDate());
    				string_date_new_other=tempDate+"/"+tempMonth+"/"+date_new_other.getFullYear();
    				text_insert +='		<tr class="tr_decorado">';
    				text_insert +='			<td class="th_decorado" style="text-align: center"> <input type="text" name="expireDateInput3_'+i+'" id="expireDateInput3_'+i+'" onclick="$(this).datepicker({changeMonth: true,changeYear: true});$(this).datepicker().datepicker(\'show\')" value="'+string_date_new_other+'" class="required form_input_align" readonly="true" title="Ingrese fecha de expiraci&oacute;n."/> </td>';
                 	text_insert +='			<td class="th_decorado" style=""><input type="hidden" name="detail_'+i+'" value="Abono por cobrar ('+(i+1)+' de '+amountPayment+')"> Abono por cobrar ('+(i+1)+' de '+amountPayment+') </td>';
                 	text_insert +='			<td class="th_decorado" style="text-align: center"> <input type="text" name="amount3_'+i+'" id="amount3_'+i+'" value="'+$("#frecuenciaTemp_3").val()+'" onChange="sumUp('+amountPayment+')" class="required numbersOnly" style="border:1px solid #959595; margin-left:0.2em; width:40px" title="Ingrese el importe a cobrar."/> Bs.</td>';
                 	text_insert +='		</tr>';
                 	switch(parseInt(frequencyPayment,10)){
	                 	case 0:
	                     	ndays=ndays+7;
	                 	  break;
	                 	case 1:
	                 		nmonth=nmonth+1;
	                 	  break;
	                 	case 2:
		                	nmonth=nmonth+2;
		             	  break;
		             	case 3:
		                	nmonth=nmonth+3;
		             	  break;
		             	case 4:
		                	nmonth=nmonth+6;
		             	  break;
		             	default:
		             		years=years+1;
                 	}
             	}
           		text_insert +='    		</tbody>';
           		text_insert +='		</table>';
        	}
        	$('#paidPlan').html(text_insert);
        }	
</script>
</head>

<body>
<div id="top-wrap">
	<%@include file="../../head.jsp"  %>
	<div id="bodySpace">
		
	    <div class="clearfix" id="middle" style="position: absolute">  <!-- aqui va la ruta -->
	        <!-- aqui va el arbol de entrada -->
	        <div id="breadcrumb">
	            <ul>
                	<li><a href="<spring:url value="/mainFront?" htmlEscape="true" />">Home</a></li>	
                    <li><span style="color:#666"><fmt:message key="title.transactions"/></span></li>
                    <li class="current-page"><span class="end"><span class="middle"><fmt:message key="title.buyProducts"/></span></span></li>
                </ul>
	        </div>
	    </div>
	    
	    <div id="principal">
            <!-- izquierda -->
            <div class="cuerpo2y" style="border: 0px solid"><br/><br/><!-- estos break son necesarios ya q uso absolute en css  cuerpo izquierdo-->
                <div class="izq">
					<%-- <%@include file="../../bodyIzq.jsp" %>	 --%>
                </div>
                
                <div class="der" style="border: 0px solid">
					<h2 class="decorado"><fmt:message key="title.buyProducts"/></h2><br/><br/> 
					
					<div id="imgLoad" style="float: left;width: 100%;display: none;"><img src="<c:url value="/resources/images/imgLoad/ajax-loader.gif" />" width="32" height="32" alt="ajax-loader.gif" style="position:absolute; top:30%; left:50%;"/></div> 
					<div id="listBuy">

					<div id="dialogNewPharmacyProduct"></div> 					
					<div id="dialogNewVisitor"></div> <!-- This is to new Visitor -->				
						<fieldset>		
							<legend><fmt:message key="title.search"/></legend>
							<table class="miReporte" style="width: 100%">
								<tr>
									<td> 
										<label for="_providerId" ><b><fmt:message key="form.provider"/> :</b></label>					
										<select name="_providerId" id="_providerId"  title="<fmt:message key="show.form.selected.provider"/>">
											<option value=""><fmt:message key="form.selected"/></option>
											<c:forEach var="item" items="${listProvider}">
												<option value="${item.providerId}">${item.name}</option>
											</c:forEach> 
										</select>
										&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
										<select name="_searchByList" id="_searchByList"  title="<fmt:message key="show.form.default"/>">
											<option value=""><fmt:message key="form.selected"/></option>
											<option value="1"><fmt:message key="title.listMissing"/></option>
											<option value="2"><fmt:message key="title.listExistenceMinimum"/></option>
											<option value="3"><fmt:message key="title.listProducts"/></option>
										</select>
										&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
										<input type="text" id="searchName" class="lettersOnly" style="border:1px solid #959595; margin-left:0.2em;" placeholder="<fmt:message key="form.productName"/>">
										<input type="text" id="searchCode" class="numbersOnly" style="border:1px solid #959595; margin-left:0.2em;" placeholder="<fmt:message key="form.code"/>">	
										<input type="text" id="searchCodeBar" class="numbersOnly" style="border:1px solid #959595; margin-left:0.2em;" placeholder="<fmt:message key="form.codeBar"/>">	
										<input type="button" value="<fmt:message key="button.search"/>" onclick="" class="boton" title="<fmt:message key="button.search"/>"/>
										<%-- <img src="<c:url value="/resources/images/imgLoad/ajax-loader.gif" />"/> --%>
											
									</td>
								</tr>
							</table> 
							<div id="mainContainerSearch"></div>
							<br/><br/>
						</fieldset>		
						<br/>
						<fieldset>		
							<legend><fmt:message key="title.dataBuy"/></legend>
							<table class="miReporte" style="width: 100%">
								<tr>
									<td> 
										<label for="billDate" ><b><fmt:message key="form.billDate"/> :</b></label>					
										<input type="text" name="billDate" id="billDate" style="border:1px solid #959595; margin-left:0.2em;" readonly="true" onclick="$(this).datepicker({changeMonth: true,changeYear: true,numberOfMonths: 1});$(this).datepicker().datepicker('show');">
										&nbsp;&nbsp;&nbsp;&nbsp;
										<label for="nroBill" ><b><fmt:message key="form.nroBill"/> :</b></label>	
										<input type="text" name="nroBill" id="nroBill" style="border:1px solid #959595; margin-left:0.2em;">	
										&nbsp;&nbsp;&nbsp;&nbsp;
										<label for="nit" ><b><fmt:message key="form.nit"/> :</b></label>	
										<input type="text" name="nit" id="nit" style="border:1px solid #959595; margin-left:0.2em;">	
										&nbsp;&nbsp;&nbsp;&nbsp;
										<label for="authorization" ><b><fmt:message key="form.authorization"/> :</b></label>	
										<input type="text" name="authorization" id="authorization" style="border:1px solid #959595; margin-left:0.2em;">	
									</td>
								</tr>
							</table> 
							<table class="tabla_decorado" style="width: 100%">
								<thead>
									<tr>
										<th width="3%" class="th_decoradoRowspan"><fmt:message key="table.num"/></th>	
										<th width="15%" class="th_decoradoRowspan"><fmt:message key="table.code"/></th>
										<th width="20%" class="th_decoradoRowspan"><fmt:message key="table.detail"/></th>
										<th width="10%" class="th_decoradoRowspan"><fmt:message key="table.quantity"/></th>
										<th width="9%" class="th_decoradoRowspan"><fmt:message key="table.cu"/></th>
										<th width="9%" class="th_decoradoRowspan"><fmt:message key="table.bonus"/></th>
										<th width="9%" class="th_decoradoRowspan"><fmt:message key="table.totalSDesc"/></th>
										<th width="9%" class="th_decoradoRowspan"><fmt:message key="table.discount"/></th>
										<th width="9%" class="th_decoradoRowspan"><fmt:message key="table.totalCDesc"/></th>
										<th width="7%" class="th_decoradoRowspan"><fmt:message key="table.actions"/></th>
									</tr>
								</thead>
								<tbody>
									<c:set var="i" value="1"/>
									<c:forEach items="${userPharmacyActive}" var="userPhar">                                	
										<tr class="tr_decorado">
											<td class="th_decorado" style="text-align: center">${i}</td>
											<td class="th_decorado">${userPhar.userpharmacyPK.userId}</td>
											<td class="th_decorado">${userPhar.user.login}</td>
											<td class="th_decorado">${userPhar.user.name}</td>
											<td class="th_decorado">${userPhar.user.lastName}</td>
											<td class="th_decorado">${userPhar.user.ci}</td>
											<td class="th_decorado">${userPhar.pharmacy.name}</td>
											<td class="th_decorado">${userPhar.pharmacy.name}</td>
										</tr>
		                            	<c:set var="i" value="${i+1}"/>
									</c:forEach>
									<c:if test="${(empty userPharmacyActive)}">
		                           		<tr class="tr_decorado">
		                           			<td class="td_decorado" colspan="10" style="text-align:center"><span style="color:red"><fmt:message key="show.noExistDataBuyProduct"/></span></td>
		                           		</tr>
		                           </c:if>
								</tbody>
								<tbody>
	                           		<tr class='tr_decorado'>
										<td class='td_decorado' colspan="8"><label>son: <b>Sesenta Bolivianos</b></label></td>
										<td class='td_decorado' colspan="2" align="right"><label>total: <b>60</b></label></td>
									</tr>
								</tbody>
							</table>
							
							<br/>
							<table class="miReporte" style="width: 100%">							
								<tr>
									<td> 
										<label for="_visitorId" ><b><fmt:message key="form.visitor"/> :</b></label>					
										<select name="_visitorId" id="_visitorId"  title="<fmt:message key="show.form.selected.visitor"/>">
											<option value=""><fmt:message key="form.selected"/></option>
										</select>																	
										<label class="error">*</label>		
										&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;			
										<input type="button" value="<fmt:message key="button.add"/> <fmt:message key="form.visitor"/>" onclick="" class="boton addNewVisitor" title="<fmt:message key="button.add"/> <fmt:message key="form.visitor"/>"/>																				
									</td>
								</tr>
								<tr>
									<td> 
										<label><b><fmt:message key="form.typeBuy"/> :</b></label>					
									    <input type="radio" name="searchTypeBuy" id="searchTypeBuy_0" value="0" class="required " checked="checked" /><label for="searchTypeBuy_0">&nbsp;&nbsp;Contado &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
									    <input type="radio" name="searchTypeBuy" id="searchTypeBuy_1" value="1" class="required " /><label for="searchTypeBuy_1">&nbsp;&nbsp;Credito &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
	                                	<label class="error">*</label>	
										<div id="typeBuyDiv" style="clear: both; display: none;">
											<br/>
											<label><b><fmt:message key="form.typePayment"/> :</b></label>
											<input type="radio" name="searchTypePayment" id="frecuenciaTemp_1" value="1" class="required " onClick="$.fn.selectRadioTypePayment(this)" /><label for="frecuenciaTemp_1">&nbsp;&nbsp;Un solo pago &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
								    		<input type="radio" name="searchTypePayment" id="frecuenciaTemp_3" value="3" class="required " onClick="$.fn.selectRadioTypePayment(this)" /><label for="frecuenciaTemp_3">&nbsp;&nbsp;Mas de un Pago &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
										    <label class="error">*</label>
										    <div id ="MainContainer" style="clear: both;display: none;"></div>
										</div>
									</td>									
								</tr>
								<tr>
									<td> 
										<div id="divShowBr" style="clear: both; display: none;"><br/></div>
										<label for="_remark" ><b><fmt:message key="form.remark"/> :</b></label>	
										<input type="text" name="_remark" id="_remark" style="border:1px solid #959595; margin-left:0.2em;">										
									</td>
									<td> 
										<input type="button" value="<fmt:message key="form.registerBuy"/>" onclick="" class="boton" title="<fmt:message key="form.registerBuy"/>"/>																				
									</td>
								</tr>
							</table> 
						</fieldset>						
					</div>	                                
                </div>
            </div><!--end of leftPan-->
            
            <div class="yDer" style="border: 1px solid #ccc;">
                  <%@include file="../../notices.jsp" %>                       
            </div><!--end of rightPan-->
        </div><!--end main content -->
	</div>
</div>
</body>
</html>
